﻿using System;
using System.ComponentModel;
using Microsoft.WowAddonStudio.FrameXml.Serialization;
using Microsoft.WowAddonStudio.FrameXml.Serialization.Attributes;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Descriptors.Filters
{
    public class InheritedPropertyDescriptorFilter : PropertyDescriptorFilter
    {
        /// <summary>
        /// Filters the specified control.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyDescriptor">The property descriptor.</param>
        /// <returns></returns>
        public override PropertyDescriptor Filter(object instance, PropertyDescriptor propertyDescriptor)
        {
            if (!(instance is IFrameXmlComponent))
                throw new ArgumentException("Only FrameXML component can be filtered.", "instance");

            var control = instance as IFrameXmlComponent;
            var inheritableObject = control.SerializationObject as InheritableObject;
            if (inheritableObject != null && inheritableObject.InheritedObject != null)
            {
                if (inheritableObject.HasInheritedValue(propertyDescriptor.Name))
                {
                    object defaultValue = inheritableObject.GetInheritedValue<object>(propertyDescriptor.Name);
                    if(defaultValue != null)
                        return TypeDescriptor.CreateProperty(propertyDescriptor.ComponentType, propertyDescriptor, new InheritedAttribute(true), new DefaultValueAttribute(defaultValue));
                }
            }

            return propertyDescriptor;
        }
    }
}